package com.graduation.sports.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.ToastUtils;
import com.graduation.sports.R;
import com.graduation.sports.base.BaseActivity;
import com.graduation.sports.ui.login.SportsLoginActivity;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.blankj.utilcode.util.AppUtils.exitApp;

/**
 * Created by apc_allen
 * date : 2/17/21
 * description :
 */
public class SplashActivity extends BaseActivity {
    private boolean afterGetPermission = false;
    private boolean afterInitApp = false;
    private ImageView bg;
    private static final String[] ACTIVITY_RECOGNITION_PERMISSION = {Manifest.permission.ACTIVITY_RECOGNITION};

    @Override
    protected int getLayout() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initDataAndEvent(Bundle savedInstanceState) {
        bg = findView(R.id.splash_bg);
//        jumpToLogin();
        initPermissions();


    }

    protected void initPermissions() {
        RxPermissions rxPermissions = new RxPermissions(this);
        // 定位权限是高版本获取Wifi名称需要的
        Disposable subscribe = rxPermissions.requestEachCombined(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CAMERA)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) {
                        if (permission.granted) { // 成功获取所有权限
                            afterGetPermission = true;
                            checkSportPermission();
                        } else if (permission.shouldShowRequestPermissionRationale) { // 选择禁止,但没有选择"以后不再询问"
                            showToast("获取权限失败,请添加权限");
                            Observable.timer(2, TimeUnit.SECONDS)
                                    .subscribe(new Consumer<Long>() {
                                        @Override
                                        public void accept(Long aLong) throws Exception {
                                            initPermissions();
                                        }
                                    });
                        } else { // 选择了"以后不在询问"
                            showToast("获取权限失败,请到\"设置\"中添加权限");
                            Observable.timer(2, TimeUnit.SECONDS)
                                    .subscribe(new Consumer<Long>() {
                                        @Override
                                        public void accept(Long aLong) throws Exception {
                                            exitApp();
                                        }
                                    });
                        }
                    }
                });
    }

    private void checkSportPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // 检查该权限是否已经获取
            int get = ContextCompat.checkSelfPermission(SplashActivity.this, ACTIVITY_RECOGNITION_PERMISSION[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (get != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求自动开启权限
                ActivityCompat.requestPermissions(SplashActivity.this, ACTIVITY_RECOGNITION_PERMISSION, 321);
            } else {
                jumpToLogin();
            }
        } else {
            jumpToLogin();
        }
    }
    private void jumpToLogin() {
        new Thread() {
            @Override
            public void run() {
                SystemClock.sleep(1000);
                //                openActivity(SportsLoginActivity.class);
                startActivity(new Intent(SplashActivity.this, SportsLoginActivity.class));

                //                openActivity(MainActivity.class);
                finish();
            }
        }.start();

//        new Thread() {
//            @Override
//            public void run() {
//                SystemClock.sleep(1000);
////                openActivity(SportsLoginActivity.class);
//                startActivity(new Intent(SplashActivity.this, SportsLoginActivity.class));
//
////                openActivity(MainActivity.class);
//                finish();
//            }
//        }.start();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    //提示用户手动开启权限
                    new AlertDialog.Builder(this)
                            .setTitle("健康运动权限")
                            .setMessage("健康运动权限不可用")
                            .setPositiveButton("立即开启", (dialog12, which) -> {
                                // 跳转到应用设置界面
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivityForResult(intent, 123);
                            })
                            .setNegativeButton("取消", (dialog1, which) -> {
                                ToastUtils.showShort("没有获得权限，应用无法运行！");
                                finish();
                            }).setCancelable(false).show();
                } else {
                    jumpToLogin();
                }
            } else {
                jumpToLogin();
            }
        }
    }

}
